import {Component} from '@angular/core';
import {Events, NavController, Platform, ToastController} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {Storage} from '@ionic/storage';
import {ConfigService} from './services/config.service';
import {LoginSuccess, Logout} from './actions/auth.actions';
import {select, Store} from '@ngrx/store';
import * as authReducer from './reducers/auth.reducer';
import {HttpService} from './services/http.service';
import {AppConfig} from './common/app-config.enum';
import {UrlAndOPT} from './common/url-and-opt.enum';
import {Network} from '@ionic-native/network/ngx';
import {Connect, Disconnect} from './actions/network.actions';
import {AppMinimize} from '@ionic-native/app-minimize/ngx';
import {NavigationEnd, Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  public userPages = [
    {title: '安全中心', url: '/auth/safety-center', icon: 'ios-unlock'},
    {title: '会员信息', url: '/auth/membership-info', icon: 'ios-contact'},
    {title: '风险评估', url: '/auth/risk-rating', icon: 'ios-podium'}
  ];

  public otherPages = [
    {title: '帮助中心', url: '/help-center', icon: 'ios-heart'},
    {title: '关于我们', url: '/about-us', icon: 'ios-alert'}
  ];

  private userInfo: any;
  private deviceType: number;

  private currentUrl = null; // 当前路由地址
  private backButtonPressed = false; // 用于判断返回键是否触发

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private navCtrl: NavController,
    private storage: Storage,
    private service$: HttpService,
    private configService: ConfigService,
    private store: Store<authReducer.AuthState>,
    private network: Network,
    private appMinimize: AppMinimize,
    private router: Router,
    private events: Events,
    private toastCtrl: ToastController
  ) {
    this.initializeApp();
  }

  async initializeApp() {
    // 网络状态
    this.subscriptNetWork();
    // 版本检测
    await this.service$.detectionUpgrade();
    // 平台准备完毕
    await this.platform.ready();
    // 设置平台类型
    await this.setPlatform();
    // 获取用户信息
    await this.getUserInfo();
    this.statusBar.styleDefault();
    this.splashScreen.hide();
    this.subscriptRouter();
    this.registerBackButtonAction();
  }

  // 监听网络状态
  private subscriptNetWork() {
    // if (this.platform.is('mobile') && !this.platform.is('mobileweb')) {
    if (this.network.type === 'none' || this.network.type === 'unknown') {
      this.showToast('已断开网络连接，请检查网络后重试');
      this.store.dispatch(new Disconnect({status: 0, type: ''}));
    } else {
      this.store.dispatch(new Connect({status: 1, type: this.network.type}));
    }
    this.network.onDisconnect().subscribe(() => {
      if (this.network.type === 'none' || this.network.type === 'unknown') {
        this.showToast('已断开网络连接，请检查网络后重试');
        this.store.dispatch(new Disconnect({status: 0, type: ''}));
      }
    });
    this.network.onConnect().subscribe(() => {
      console.log('网络已连接!');
      if (!(this.network.type === 'none' || this.network.type === 'unknown')) {
        this.store.dispatch(new Connect({status: 1, type: this.network.type}));
      }
    });
    // }
  }

  // 显示通知消息
  private async showToast(msg) {
    const toast = await this.toastCtrl.create({
      message: msg || '请求数据失败',
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }

  // 设置平台类型
  private async setPlatform() {
    if (this.platform.is('android')) {
      this.deviceType = 2;
    } else if (this.platform.is('ios')) {
      this.deviceType = 3;
    }
    return await this.storage.set(AppConfig.USER_PLATFORM, this.deviceType);
  }

  // 获取用户信息
  private async getUserInfo() {
    this.userInfo = await this.storage.get(AppConfig.USER_INFO);
    if (this.userInfo && this.userInfo[AppConfig.USER_INFO_KEY]) {
      // 登录所需参数：mobile password userType deviceType
      const params = {
        mobile: this.userInfo['mobile'],
        password: this.userInfo['password'],
        userType: this.userInfo['userType'],
        deviceType: this.deviceType
      };
      // 用户执行过登录，APP启动时自动登录一次(防止登录超时状态或密码变更)
      const obj = await this.service$.doRequest(UrlAndOPT.auth_login, params).toPromise();
      if (obj) { // 刷新状态成功
        if (obj[AppConfig.USER_INFO_KEY]) {
          this.userInfo = {
            [AppConfig.USER_INFO_KEY]: obj[AppConfig.USER_INFO_KEY],
            userRole: obj['userRole'],
            userType: obj['userType'],
            toBindCard: obj['toBindCard'],
            toRestPWd: obj['toRestPWd'],
            mobile: params['mobile'],
            password: params['password']
          };
          // 更新本地用户信息后，发送登录通知
          await this.storage.set(AppConfig.USER_INFO, this.userInfo);
          this.store.dispatch(new LoginSuccess({status: 1, userInfo: this.userInfo}));
        } else {
          this.store.dispatch(new LoginSuccess({status: 1, userInfo: this.userInfo}));
        }
        // 检测用户迁移状态
        await this.service$.getUserStatus();
        // 已在登录状态时，转向手势解锁
        // await this.navCtrl.navigateForward(['/auth/gesture-lock', {isShowLink: true}]);
      } else { // 刷新状态失败，清除用户信息
        await this.service$.clearUserInfo();
        this.store.dispatch(new Logout({status: 0, userInfo: {}, response: null}));
      }
    }
    // 侦听登录状态变化
    this.store.pipe(select(authReducer.getAuth))
      .subscribe(authState => {
        this.userInfo = {...authState.userInfo};
      });
  }

  // 打开菜单对应页面
  pushPage(url) {
    if (this.userInfo && this.userInfo[AppConfig.USER_INFO_KEY]) {
      if (url === '/auth/risk-rating') { // 特殊处理风险评估跳转
        this.service$.doUndo(null, {step: '风险评估'});
      } else {
        if (url === '/auth/membership-info' && this.userInfo[AppConfig.USER_TYPE_KEY] === 2) {
          url = '/auth/membership-info-enter';
        }
        this.navCtrl.navigateForward(url);
      }
    } else {
      this.navCtrl.navigateForward(['/login']); // 未登录前往登录页面
    }
  }

  // 监听路由路径变化
  private subscriptRouter() {
    this.router.events
      .subscribe(event => {
        if (event instanceof NavigationEnd) {
          this.currentUrl = event.url; // 获取当前路由路径
        }
      });
  }

  // 点击返回按钮显示提示，2秒内再次点击最小化APP
  private registerBackButtonAction() {
    this.platform.backButton
      .subscribe(() => {
        if (this.currentUrl.indexOf('/tabs') === 0) {
          if (this.backButtonPressed) {
            this.appMinimize.minimize();
            this.backButtonPressed = false;
          } else {
            this.showToast('再按一次退出程序');
            this.backButtonPressed = true;
            setTimeout(() => this.backButtonPressed = false, 2000);
          }
        }
      });
  }

}
